local extension = Package("rfenghou_qi")
extension.extensionName = "aaa_fenghou"

local U = require "packages/utility/utility"
local RUtil = require "packages/aaa_fenghou/utility/rfenghou_util"

Fk:loadTranslationTable{
  ["rfenghou_qi"] = "哄齐",
}

local function AddWinAudio(general)
  local Win = fk.CreateActiveSkill{ name = general.name.."_win_audio" }
  Win.package = extension
  Fk:addSkill(Win)
end

local gaochanggong = General:new(extension, "rfenghou__gaochanggong", "qi", 4)
local ruzhen = fk.CreateTriggerSkill{
  name = "rfenghou__ruzhen",
  anim_type = "drawcard",
  frequency = Skill.Compulsory,
  events = {fk.GameStart, fk.RoundEnd},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      local cards = player:drawCards(3, self.name, "top", "@@rfenghou__ruzhen-inhand")
      room:setPlayerMark(player, self.name, table.simpleClone(cards))
    else
      local cards = table.filter(player:getCardIds("h"), function (id)
        return table.contains(player:getTableMark(self.name), id)
      end)
      if #cards > 0 then
        room:recastCard(cards, player, self.name)
      else
        cards = player:drawCards(3, self.name, "top", "@@rfenghou__ruzhen-inhand")
        room:setPlayerMark(player, self.name, table.simpleClone(cards))
      end
    end
  end
}
local ruzhen_maxcards = fk.CreateMaxCardsSkill{
  name = "#rfenghou__ruzhen_maxcards",
  exclude_from = function(self, player, card)
    return card and card:getMark("@@rfenghou__ruzhen-inhand") ~= 0
  end,
}
ruzhen:addRelatedSkill(ruzhen_maxcards)
gaochanggong:addSkill(ruzhen)
Fk:loadTranslationTable{
  ["rfenghou__gaochanggong"] = "高长恭",
  ["#rfenghou__gaochanggong"] = "赤透假面",
  ["illustrator:rfenghou__gaochanggong"] = "珊瑚虫",
  ["designer:rfenghou__gaochanggong"] = "ab",
  ["cv:rfenghou__gaochanggong"] = "折翼",

  ["rfenghou__ruzhen"] = "入阵",
  [":rfenghou__ruzhen"] = "锁定技，游戏开始时，你摸三张牌并展示之；轮次结束时，你展示因“入阵”获得的牌并重铸之，若无牌可重铸，你摸三张牌并展示之。你因“入阵”获得的牌不计入手牌上限。",
  ["@@rfenghou__ruzhen-inhand"] = "入阵",

  ["$rfenghou__ruzhen1"] = "（鼓声）",
  ["$rfenghou__ruzhen2"] = "家事亲切，不觉遂危。",
  ["$rfenghou__ruzhen3"] = "兰陵亲至，贼虏得破，且速与援。",
  ["~rfenghou__gaochanggong"] = "天颜，何由得见！",
}

local qihuangong = General:new(extension, "rfenghou__jiangxiaobai", "qi", 4)

local rfenghou__rangyi = fk.CreateTriggerSkill{
  name = "rfenghou__rangyi",
  events = {fk.CardUsing},
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) and (data.card.name == "jink" or data.card.name == "nullification") then
      return table.find(player.room.alive_players, function (p)
        return p ~= target and p:getHandcardNum() > 1 and not table.contains(player:getTableMark(self.name), p.id)
      end)
    end
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local targets = table.filter(room.alive_players, function (p)
      return p ~= target and p:getHandcardNum() > 1 and not table.contains(player:getTableMark(self.name), p.id)
    end)
    local tos = room:askForChoosePlayers(player, table.map(targets, Util.IdMapper), 1, 1, "#rfenghou__rangyi-choose", self.name, true)
    if #tos > 0 then
      self.cost_data = {tos = tos}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = room:getPlayerById(self.cost_data.tos[1])
    room:addTableMark(player, self.name, to.id)
    local num = to:getHandcardNum() // 2
    local cards = room:askForCardsChosen(player, to, num, num, "h", self.name)
    room:throwCard(cards, self.name, to, player)
    if not player.dead and table.every(room.alive_players, function (p)
      return table.contains(player:getTableMark(self.name), p.id)
    end) then
      room:setPlayerMark(player, self.name, 0)
    end
  end,
}
qihuangong:addSkill(rfenghou__rangyi)

local rfenghou__hemeng = fk.CreateTriggerSkill{
  name = "rfenghou__hemeng",
  events = {fk.CardUsing},
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and ((data.card.multiple_targets and data.card.type == Card.TypeTrick)
    or (data.card.name == "fire__slash" or data.card.name == "thunder__slash" or data.card.name == "ice__slash"))
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    local targets = table.map(table.filter(room.alive_players, function (p)
      return not target:isProhibited(p, data.card)
      and data.card.skill:modTargetFilter(p.id, {}, target, data.card, true)
    end), Util.IdMapper)
    if #targets == 0 then return false end
    local num = math.min(#room.alive_players // 2, #targets)
    local prompt = "#rfenghou__hemeng-"..(target ~= player and "mustself" or "choose")..":::"..data.card:toLogString()..":"..num
    local _, dat = room:askForUseActiveSkill(player, "rfenghou__hemeng_active", prompt, true,
    {targets = targets, target_num = num, mustChooseSelf = target ~= player})
    if dat then
      room:sortPlayersByAction(dat.targets)
      self.cost_data = {tos = dat.targets}
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    data.tos = table.map(self.cost_data.tos, function (id) return {id} end)
    room:sendLog{type = "#ChangeTarget", from = target.id, arg = data.card:toLogString(), to = self.cost_data.tos}
  end,
}
qihuangong:addSkill(rfenghou__hemeng)

local rfenghou__hemeng_active = fk.CreateActiveSkill{
  name = "rfenghou__hemeng_active",
  card_num = 0,
  card_filter = Util.FalseFunc,
  target_filter = function(self, to_select, selected)
    return table.contains(self.targets or {}, to_select) and #selected < self.target_num
  end,
  feasible = function(self, selected)
    if self.mustChooseSelf and not table.contains(selected, Self.id) then return false end
    return #selected == self.target_num
  end,
}
Fk:addSkill(rfenghou__hemeng_active)

local rfenghou__muxian = fk.CreateTriggerSkill{
  name = "rfenghou__muxian$",
  events = {fk.Damage},
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target and not target.dead and data.to == player
  end,
  on_cost = function (self, event, target, player, data)
    local room = player.room
    self.cost_data = {tos = {target.id}}
    if target.kingdom == "qi" then
      return room:askForSkillInvoke(target, self.name, nil, "#rfenghou__muxian-recover:"..player.id)
    else
      return room:askForSkillInvoke(player, self.name, nil, "#rfenghou__muxian-draw:"..target.id)
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if target.kingdom == "qi" then
      room:recover { num = 1, skillName = self.name, who = player, recoverBy = target }
    else
      player:drawCards(1, self.name)
      if not target.dead then
        target:drawCards(1, self.name)
      end
      room:changeKingdom(target, "qi", true)
    end
  end,
}
qihuangong:addSkill(rfenghou__muxian)
AddWinAudio(qihuangong)
Fk:loadTranslationTable{
  ["rfenghou__jiangxiaobai"] = "姜小白", -- 齐桓公
  ["#rfenghou__jiangxiaobai"] = "一匡天下",
  ["illustrator:rfenghou__jiangxiaobai"] = "啪啪三国",
  ["designer:rfenghou__jiangxiaobai"] = "扬林",
  ["cv:rfenghou__jiangxiaobai"] = "丫奶",

  ["rfenghou__rangyi"] = "攘夷",
  [":rfenghou__rangyi"] = "一名角色使用【闪】或【无懈可击】时，你可以弃置未以此法弃置过的另一名角色半数手牌（向下取整）；你以此法弃置过所有存活角色的牌后，重置此技能。",
  ["#rfenghou__rangyi-choose"] = "攘夷：你可以弃置一名角色一半的手牌！",

  ["rfenghou__hemeng"] = "合盟",
  [":rfenghou__hemeng"] = "一名角色使用属性【杀】或多目标锦囊牌时，你可以将此牌目标改为场上半数由你指定的角色（向下取整，不足则全选）；若使用牌的角色不为你，你需为目标之一。",
  ["#rfenghou__hemeng-choose"] = "合盟：你可重新选择 %arg2 名角色作为%arg的目标",
  ["#rfenghou__hemeng-mustself"] = "合盟：你可重新选择 %arg2 名角色作为%arg的目标（须包含你！）",
  ["rfenghou__hemeng_active"] = "合盟",
  ["#ChangeTarget"] = "%from 使用的 %arg 目标被改为 %to",

  ["rfenghou__muxian"] = "募贤",
  [":rfenghou__muxian"] = "主公技，一名角色对你造成伤害后，若其为齐势力，其可以令你回复一点体力；若为其他势力，你可以与其各摸一张牌，再将其改为齐势力。",
  ["#rfenghou__muxian-recover"] = "募贤:你可以令 %src 回复一点体力",
  ["#rfenghou__muxian-draw"] = "募贤:你可以与 %src 各摸一张牌，再将其改为齐势力",

  ["$rfenghou__rangyi1"] = "受先君专征之任，内修政治，外攘夷狄。",
  ["$rfenghou__rangyi2"] = "尔贡包茅不入，王祭无以缩酒，寡人是征。",
  ["$rfenghou__hemeng1"] = "北伐山戎、南至召陵；九合诸侯，一匡天下！",
  ["$rfenghou__hemeng2"] = "凡我同盟之人，既盟之后，言归于好。",
  ["$rfenghou__muxian1"] = "布衣之士可轻爵禄，万乘之主岂可轻贤士？",
  ["$rfenghou__muxian2"] = "君者劳于索人，寡人得仲父，何为不易？",
  ["~rfenghou__jiangxiaobai"] = "仲父之谋，百不失一；寡人不听，是有今日……",
  ["$rfenghou__jiangxiaobai_win_audio"] = "既当一人，身有何劳？垂衣裳而天下定。",
}

local suqingyue = General:new(extension, "rfenghou__suqingyue", "qi", 4, 4, General.Female)

Fk:loadTranslationTable{
  ["rfenghou__suqingyue"] = "苏清月",
  ["#rfenghou__suqingyue"] = "霜刃悬旌",
  ["illustrator:rfenghou__suqingyue"] = "啪啪三国",
  ["designer:rfenghou__suqingyue"] = "祭祀",
  ["cv:rfenghou__suqingyue"] = "邪恶母蟑螂",

  ["$rfenghou__guijian1"] = "剑斩世间不平事，浮云深处藏功名。",
  ["$rfenghou__guijian2"] = "生者为过客，死者为归人。天地一逆旅，同悲万古尘。",
  ["~rfenghou__suqingyue"] = "生无恋，死无厌，黄泉无相见。",
}

local guijian_skills = {}

--- 判断蓄势状态不同
---@param player Player
---@param to Player
---@return boolean
local function compareReadySkillState(player, to)
  if player == to then return false end
  local states = {}
  for _, s in ipairs(player:getAllSkills()) do
    if s.RfenghouReadySkill then
      table.insertIfNeed(states, player:getMark("@@rfenghou_readying:::"..s.name))
    end
  end
  if #states == 0 then return false end
  local to_states = {}
  for _, s in ipairs(to:getAllSkills()) do
    if s.RfenghouReadySkill then
      table.insertIfNeed(to_states, to:getMark("@@rfenghou_readying:::"..s.name))
    end
  end
  if #to_states == 0 then return false end
  return #states > 1 or #to_states > 1 or states[1] ~= to_states[1]
end

local zongjian = fk.CreateTriggerSkill{
  name = "rfenghou__zongjian",
  mute = true,
  events = {fk.GameStart, fk.TargetSpecified, fk.TurnStart},
  can_trigger = function(self, event, target, player, data)
    if not player:hasSkill(self) then return false end
    if event == fk.GameStart then
      return true
    elseif event == fk.TurnStart then
      return target == player and player:getMark("rfenghou__zongjian_limit") == 0
    elseif event == fk.TargetSpecified then
      if target == player and data.firstTarget then
        local tars = AimGroup:getAllTargets(data.tos)
        local tos = {}
        for _, pid in ipairs(tars) do
          local to = player.room:getPlayerById(pid)
          if compareReadySkillState(player, to) then
            table.insertIfNeed(tos, pid)
          end
        end
        if #tos > 0 then
          self.cost_data = {tos = tos}
          return true
        end
      end
    end
  end,
  on_cost = function (self, event, target, player, data)
    if event == fk.TurnStart then
      return player.room:askForSkillInvoke(player, self.name, nil, "#rfenghou__zongjian-limit")
    end
    return true
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart then
      player:broadcastSkillInvoke(self.name)
      room:notifySkillInvoked(player, self.name, "special")
      for _, p in ipairs(room:getAlivePlayers()) do
        room:handleAddLoseSkills(p, "rfenghou__xuanjian")
      end
    elseif event == fk.TurnStart then
      room:setPlayerMark(player, "rfenghou__zongjian_limit", 1)
      player:broadcastSkillInvoke(self.name)
      room:notifySkillInvoked(player, self.name, "big")
      for i = 1, 1 do
        local new = table.find(guijian_skills, function (s)
          return Fk.skills[s] ~= nil and not player:hasSkill(s, true, true)
        end)
        if not new then break end
        local tag = player.tag["rfenghou__zongjian_skill"] or {}
        table.insert(tag, new)
        player.tag["rfenghou__zongjian_skill"] = tag
        room:handleAddLoseSkills(player, new)
      end
    else
      --player:broadcastSkillInvoke(self.name)
      local tos = table.simpleClone(self.cost_data.tos)
      room:notifySkillInvoked(player, self.name, "offensive", tos)
      data.disresponsiveList =  data.disresponsiveList or {}
      table.insertTableIfNeed(data.disresponsiveList, tos)
    end
  end,
  on_lose = function (self, player, is_death)
    player.room:setPlayerMark(player, "rfenghou__zongjian_limit", 0)
  end,
}

local zongjian_delay = fk.CreateTriggerSkill{
  name = "#rfenghou__zongjian_delay",
  mute = true,
  priority = 0.99,
  events = {fk.TurnEnd},
  can_trigger = function(self, event, target, player, data)
    return player.tag["rfenghou__zongjian_skill"]
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local skills = table.simpleClone(player.tag["rfenghou__zongjian_skill"])
    player.tag["rfenghou__zongjian_skill"] = nil
    if #player.room.logic:getEventsOfScope(GameEvent.Death, 1, function(e)
      local death = e.data[1]
      return death.damage and death.damage.from == player
    end, Player.HistoryTurn) == 0 then
      room:handleAddLoseSkills(player, "-"..table.concat(skills, "|-"))
    end
  end,
}
zongjian:addRelatedSkill(zongjian_delay)

suqingyue:addSkill(zongjian)


Fk:loadTranslationTable{
  ["rfenghou__zongjian"] = "纵剑",
  [":rfenghou__zongjian"] = "游戏开始时，所有角色获得“玄剑”；锁定技，你使用牌指定蓄势状态与你不同的角色无法响应；限定技，回合开始时，你可以于本回合获得“归剑”，回合结束时，若你本回合杀死过角色，永久获得。",
  ["#rfenghou__zongjian-limit"] = "纵剑：你可以于本回合获得“归剑”",

  ["$rfenghou__zongjian1"] = "满堂花醉三千客，一剑霜寒十四州。",
  ["$rfenghou__zongjian2"] = "龙吟涧底寒潭彻，剑在匣中作狂歌。",
}

local xuanjian = fk.CreateTriggerSkill{
  name = "rfenghou__xuanjian",
  anim_type = "offensive",
  events = {fk.Damage, fk.Damaged},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and target == player
    and player:getMark("@@rfenghou_readying:::rfenghou__xuanjian") == 0
  end,
  on_cost = function (self, event, target, player, data)
    return player.room:askForSkillInvoke(player, self.name, nil, "#rfenghou__xuanjian-"..(event == fk.Damage and "damage" or "nondamage"))
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    player.room:broadcastPlaySound("./packages/aaa_fenghou/audio/skill/rfenghou__xuanjian1")
    local cards = room:getNCards(3)
    room:moveCardTo(cards, Card.Processing, nil, fk.ReasonJustMove, self.name, nil, true, player.id)
    room:delay(800)
    if not player.dead then
      local get = table.filter(cards, function (id)
        return room:getCardArea(id) == Card.Processing and
        (not not Fk:getCardById(id).is_damage_card) == (event == fk.Damage)
      end)
      if #get > 0 then
        player.room:broadcastPlaySound("./packages/aaa_fenghou/audio/skill/rfenghou__xuanjian2")
        room:obtainCard(player, get, true, fk.ReasonJustMove, player.id, self.name)
      end
    end
    room:cleanProcessingArea(cards, self.name)
  end,
}
xuanjian.RfenghouReadySkill = true
Fk:addSkill(xuanjian)

Fk:loadTranslationTable{
  ["rfenghou__xuanjian"] = "玄剑",
  [":rfenghou__xuanjian"] = "蓄势技，你造成/受到伤害后，可以亮出牌堆顶的三张牌并获得其中的伤害牌/非伤害牌。",
  ["@@rfenghou_readying:::rfenghou__xuanjian"] = "玄剑 蓄势中",
  ["#rfenghou__xuanjian-damage"] = "玄剑：你可以牌堆顶的3张牌，获得其中的伤害牌",
  ["#rfenghou__xuanjian-nondamage"] = "玄剑：你可以牌堆顶的3张牌，获得其中的非伤害牌",

  ["$rfenghou__xuanjian1"] = "恨我音灭，怨我血枯，折髓笑去，鬼神诛。",
  ["$rfenghou__xuanjian2"] = "旦为朝云，暮为行雨。朝朝暮暮，阳台之下。",
}

for loop = 0, 30, 1 do
  local guijian = fk.CreateTriggerSkill{
    name = loop == 0 and "rfenghou__guijian" or "rfenghou"..loop.."__guijian",
    priority = 1 - loop / 1000,
    anim_type = "offensive",
    frequency = Skill.Compulsory,
    events = {fk.DamageCaused, fk.DamageInflicted},
    can_trigger = function(self, event, target, player, data)
      if player:hasSkill(self) and target == player then
        local to = (event == fk.DamageCaused) and data.to or data.from
        return to and compareReadySkillState(player, to)
      end
    end,
    on_use = function (self, event, target, player, data)
      if event == fk.DamageCaused then
        player.room:broadcastPlaySound("./packages/aaa_fenghou/audio/skill/rfenghou__guijian1")
        data.damage = data.damage + 1
      else
        player.room:broadcastPlaySound("./packages/aaa_fenghou/audio/skill/rfenghou__guijian2")
        data.damage = data.damage - 1
      end
    end,
  }

  table.insert(guijian_skills, guijian.name)
  Fk:addSkill(guijian)
  Fk:loadTranslationTable{
    [guijian.name] = "归剑",
    [":"..guijian.name] = "锁定技，你造成/受到伤害时，若其蓄势状态与你不同，伤害+1/-1。",
  }
end

suqingyue:addRelatedSkill("rfenghou__xuanjian")
suqingyue:addRelatedSkill("rfenghou__guijian")



return extension
